<template>
    <div class="page">
        <Header title="LBS投放" left-arrow />
        <div class="content">
            <selected-tags ref="selectedTagRef" :citys="citys" @changeCity="changeCity"></selected-tags>
            <put-strategy ref="putStrategyRef" class="mt12" :media-type-selected="defaultMediaType" @onTabChange="onTabChange" @changeData="strategyChange"></put-strategy>
        </div>
        <div class="bottom">
            <div class="bottom-text">
                <div v-if="curTab===1" class="family-box">
                    投放{{ numberWithCommas(screenPointNum) }}个智能屏，{{ numberWithCommas(lcdPointNum) }}个LCD，覆盖{{ numberWithCommas(people) }}人
                </div>

                <div class="total-amount">
                    <span v-if="curTab === 1" class="amount">¥{{ formatNumber(price) }}</span>
                    <span v-else>-</span>
                    <span>（按刊例价的0.5折计算）</span>
                </div>
                <div v-if="curTab === 1" class="cph-price">
                    <div>
                        <span>CPH：</span>
                        <span class="price">
                            <template v-if="+faimaly === 0">--</template>
                            <template v-else>
                                {{ cph.value }}元/户/周
                            </template>
                        </span>
                        <!-- <van-popover v-model:show="showPopover" theme="dark" placement="top-end">
                            <div class="pop-content">
                                仅针对住宅类楼盘计算每户每周触达成本，您的投放策略覆盖{{ cph.premisesNum }}个中高端住宅楼盘，其中{{ cph.screenPointNum }}个智能屏，{{ cph.lcdPointNum }}个LCD，{{ cph.framePointNum }}个海报
                            </div>
                            <template #reference>
                                <img src="@/assets/img/cph-tips.png" alt="">
                            </template>
                        </van-popover> -->
                    </div>
                </div>
            </div>

            <div class="fe-btns">
                <div class="left" @click="goBack">
                    上一步
                </div>
                <div :class="curTab === 2&& 'disable'" class="right" @click="nextStep">
                    下一步
                </div>
            </div>
        </div>
    </div>
</template>

<script name="productsLbsStrategyCheck" lang="ts" setup>
import { reactive, ref } from 'vue';
import { store } from '@/store';
import { useRouter } from 'vue-router';
import Header from '@/components/Header/index.vue';
import PutStrategy from '@/views/products/selectByTag/components/PutStrategy.vue';
import SelectedTags from './components/SelectedTags.vue';
import { Toast as myToast } from 'vant';
import { numberWithCommas, formatNumber } from '@/utils/filters';
import { MediaItem, StrategyItemData, cityModel, StrategyResultData } from '@/views/products/selectByTag/strategy.module';
import { StrategyStatisticsReq, strategySpecsItem, getStrategyStatistics, saveStrategySpecs } from '@/api/brandBreakout';
import { clearLoading, showLoading } from '@/api';

const router = useRouter();
const projectId: string = store.state.app.home.projectId || '';
const selectByLbs = store.state.app.selectByLbs;
interface AdderssModel {
    longitude: number,
    latitude: number,
    radius: number,
}
let citys = selectByLbs?.addresses as unknown as cityModel[]; // 地址
let addresses: AdderssModel[] = citys.map(item => {
    return {
        longitude: item.lng,
        latitude: item.lat,
        radius: item.radius,
    } as AdderssModel;
});


const defaultMediaType = selectByLbs?.tagBulidArr?.mediaTypes?.map(item => item.value) || [];
let mediaTypes: number[] = defaultMediaType; // 媒体类型
let strategySpecs: StrategyItemData[] = [];

const price = ref('0');
// const cph = ref('0');
const faimaly = ref(0);
const people = ref(0);
const screenPointNum = ref(0);
const lcdPointNum = ref(0);
let cph: StrategyResultData = reactive({
    framePointNum: 0,
    lcdPointNum: 0,
    premisesNum: 0,
    screenPointNum: 0,
    value: 0,
});

const curTab = ref(1); // 1.社区 2.商务
function onTabChange(val:number){
    curTab.value = val;
}

function handleParams() {
    const params: StrategyStatisticsReq = {
        businessScenario: curTab.value,
        pointSelectionMode: 0,
        projectId: projectId,
        cityCodes: [selectByLbs?.city.id],
        addresses: addresses,
        mediaTypes,
        strategySpecs: strategySpecs as unknown as strategySpecsItem[],
        areaCodes: selectByLbs?.areaList.map(item => item.id),
        premisesTypes: (selectByLbs?.tagBulidArr?.premisesType || []).map(item => item.value) as unknown as string[],
        premisesPrices: (selectByLbs?.tagBulidArr?.premisesPrice || []).map(item => item.value),
        premisesAges: (selectByLbs?.tagBulidArr?.premisesAge || []).map(item => item.value),
        inHouseRates: (selectByLbs?.tagBulidArr?.inHouseRate || []).map(item => item.value),
        parkingNums: (selectByLbs?.tagBulidArr?.parkingNum || []).map(item => item.value),
        propertyFees: (selectByLbs?.tagBulidArr?.propertyFee || []).map(item => item.value),
    };
    return params;
}

function resetData() {
    price.value = '0';
    cph = {
        framePointNum: 0,
        lcdPointNum: 0,
        premisesNum: 0,
        screenPointNum: 0,
        value: 0,
    };
    faimaly.value = 0;
    people.value = 0;
    screenPointNum.value = 0;
    lcdPointNum.value = 0;
}

// 获取投放策略信息
async function getStrategyStatisticInfo() {
    if(curTab.value === 2) {
        return;
    }
    if(!mediaTypes.length) {
        resetData();
        return myToast('媒体形式至少选择一种');
    }

    showLoading();
    let res;
    try {
        res = await getStrategyStatistics(handleParams());
        if(res){
            price.value = res.price;
            cph = res?.cph;
            faimaly.value = res.mediaResource?.resourceSummary?.coveredHouseholdNum || 0;
            people.value = res.mediaResource?.resourceSummary?.coveredPeopleNum || 0;
            screenPointNum.value = res.mediaResource?.mediaResourceSummaryList.find(item => item.mediaType === 1)?.pointNum || 0;
            lcdPointNum.value = res.mediaResource?.mediaResourceSummaryList.find(item => item.mediaType === 2)?.pointNum || 0;
        } else {
            resetData();
        }
    } catch (e) {
        console.error(e);
    } finally {
        clearLoading();
    }
}

async function strategyChange(mediaTypeList: MediaItem[], strategySpecsList:StrategyItemData[]) {
    mediaTypes = mediaTypeList.map(item => +item.value);
    strategySpecs = strategySpecsList;
    await getStrategyStatisticInfo();
}

async function changeCity(city:cityModel[]) {
    citys = city;
    addresses = citys.map(item => {
        return {
            longitude: item.lng,
            latitude: item.lat,
            radius: item.radius,
        } as AdderssModel;
    });
    await getStrategyStatisticInfo();
}
const goBack = ()=>{
    router.back();
};
async function nextStep() {
    if(!mediaTypes.length) {
        return myToast('媒体形式至少选择一种');
    }
    if(+price.value === 0) {
        return myToast('无楼盘资源');
    }
    showLoading();
    try {
        await saveStrategySpecs(handleParams());
        await router.push({name: 'productsBrandBreakoutResult', query: {
            type: 4
        }});
    } catch (error) {
        console.log(error);
    } finally {
        clearLoading();
    }
}

</script>

<style scoped lang="scss">
@import "@/styles/variables";

.mt12 {
    margin-top: 12px;
}
.page {
    background-color: #f4f4f4;
    height: 100vh;
    .content {
        padding: 12px 12px 204px;
    }
    .bottom {
        position: fixed;
        bottom: 0;
        background: #ffffff;
        width: 100%;
        border-top: 0.5px solid #f4f4f4;
        padding: 12px 0 8px;
        padding-bottom: contain(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);
        box-sizing: border-box;
        box-shadow: 0 -2px 4px 0 #ebebeb80;

        div {
            display: flex;
            padding: 0 12px;

            span {
                display: inline-block;
                font-weight: 400;
                font-size: 12px;
                color: #5b5b5b;
                height: 17px;
            }
        }

        .bottom-text {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            text-align: right;
            .family-box {
                margin-bottom: 10px;
                font-weight: 500;
                font-size: 12px;
                color: #333333;
            }
            .total-amount {
                justify-content: flex-end;
                align-items: center;
                transform: translateX(8px);
                .amount {
                    height: 21px;
                    line-height: 21px;
                    font-family: $spec_font;
                    font-size: 18px;
                    color: #e60044;
                    text-align: right;
                }
            }
            .cph-price {
                transform: translateX(18px);
                margin-top: 5px;
                justify-content: space-between;
                align-items: center;

                .price {
                    height: 17px;
                    font-weight: 600;
                    font-size: 12px;
                    color: #333333;
                    margin-right: 6px;
                }

                img {
                    width: 14px;
                    height: 14px;
                }
            }
        }

        .fe-btns {
            margin-top: 12px;
            border-top: 0.5px solid #f4f4f4;
            display: flex;
            padding: 6px 12px 0;
            margin-bottom: 8px;

            div {
                display: flex;
                justify-content: center;
                align-items: center;
            }

            .left {
                width: 120px;
                height: 38px;
                line-height: 38px;
                background: #ffffff;
                border: 0.5px solid #e60044;
                border-radius: 6px;
                font-weight: 400;
                font-size: 14px;
                color: #e60044;
                text-align: center;
                margin-right: 12px;
            }

            .right {
                width: calc(100% - 120px);
                height: 38px;
                line-height: 38px;
                background: #e60044;
                border: 0.5px solid #e60044;
                border-radius: 6px;
                font-weight: 600;
                font-size: 14px;
                color: #ffffff;
                text-align: center;
            }
            .right.disable {
                opacity: 0.7;
                pointer-events: none;
            }
            .left.disable {
                opacity: 0.7;
                pointer-events: none;
            }
        }
    }
}
.pop-content {
    padding: 10px;
    font-size: 12px;
    line-height: 19px;
    width: 280px;
}
</style>
